/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import Axios from "axios"
import { Album } from "../Models/Album.schema";
import { createAlbumDTO, updateAlbumDTO } from "../DTO/Album.dto";
import { isExistsforId, isExistsforTitle } from "../hook";

export class AlbumController {
  constructor(private readonly albumModel: typeof Album) { }

  /**
 * 创建专辑
 * @param dto 数据传输对象
 * @returns 返回创建对象
 */
  async createItem(dto: createAlbumDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await this.albumModel.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }

  /**
 * 以ID为查找依据删除专辑
 * @param id 要删除元素的唯一ID
 * @returns
  */
  async removeById(id: string) {
    try {
      if (!await isExistsforId(id, this.albumModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "删除成功",
          data: await this.albumModel.deleteOne({ _id: id }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新专辑
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateAlbumDTO) {
    try {
      if (!await isExistsforId(id, this.albumModel)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.albumModel.updateOne({ _id: id }, dto),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
  * 按专辑名称查找专辑
  * @param title 要查找的专辑名称
  * @returns 查询对象
  */
  async findByTitle(title: string) {
    try {
      if (!await this.isExist(title)) {
        //网易云查询
        const data = await Axios.get(`http://162.14.104.16:3005/search?keywords=${title}&type=10&limit=50`, { withCredentials: true })
        const res = await data.data as {
          code: number;
          result: {
            albumCount: number;
            albums: {
              id: string;//专辑id
              name: string; //名称
              type: string;//专辑类型
              publishTime: string;
              picUrl: string; // 封面
              artist: any; //艺术家
              company: string;//发行公司
              alias: object; //特别介绍
              artists: string; //艺术家
            }[];
          }
        };
        // 只录入前10条数据
        if (res.result.albumCount > 0) {
          for (let i = 0; i < res.result.albums.length; i++) {
            if (i === 80) { break; }
            let tempData = {
              //专辑唯一标识
              _id: res.result.albums[i].id,
              // 专辑名称
              title: res.result.albums[i].name,
              //封面
              cover: res.result.albums[i].picUrl,
              // 演唱者
              singer: res.result.albums[i].artists,
              //播放地址
              link: res.result.albums[i].id,
              //发布时间
              time: res.result.albums[i].publishTime,
              //专辑出品商
              company: res.result.albums[i].company,
              //特别介绍
              alias: res.result.albums[i].alias,
              // 主要演唱者
              firstSinger: res.result.albums[i].artist,
            } as createAlbumDTO

            // 添加到数据库
            await this.createItem(tempData);
            // console.log(tempData)
          }

          return {
            code: 200,
            message: '查询成功',
            data: await this.albumModel.find({ title: { $regex: eval("/" + title + "/g") } }),
          }
        }
        return {
          code: 400,
          message: '不存在查询的Title',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.albumModel.find({ title: { $regex: eval("/" + title + "/g") } }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 查找专辑
   * @param id 要查找的专辑id
   * @returns 查询对象
  sws */
  async findById(id: string) {
    try {
      if (!await isExistsforId(id, this.albumModel)) {
        if (!await isExistsforTitle(id, this.albumModel)) {
          return {
            code: 400,
            message: '不存在查询对象',
          }
        } else {
          return {
            code: 200,
            message: "查询成功",
            data: await this.albumModel.find({ title: id }),
          };
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.albumModel.find({ _id: id }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  //查询全部数据
  async findAll() {
    try {
      if (await this.albumModel.find().count() != 0)
        return {
          code: 200,
          message: "查询成功",
          data: await this.albumModel.find(),

        };
      else
        return {
          code: 400,
          message: "该数据集不存在数据"
        }
    }
    catch (error) {
      return await error;
    }
  }
  //随机获取指定条数的数据
  async findBySize(size: number) {
    try {
      return {
        code: 200,
        message: "查询成功",
        data: await this.albumModel.aggregate([{ $sample: { size: size } }])
      }

    } catch (error) {
      return error;
    }
  }
  // 获取专辑信息
  async getInfo(id: string) {
    try {
      const data = await Axios.get(`http://162.14.104.16:3005/album?id=${id}`)
      const res = data.data as {
        code: string,
        resourceState: string,
        songs: {
          ar: any;
          al: any;
          name: string,
          id: string,
        }[],
        album: {
          artists: string,
          company: string,
          picUrl: string,
          description: string
        }
      }
      if (res) {
        return {
          code: 200,
          message: "获取成功",
          data: res,
        }
      }
      else {
        return {
          code: 400,
          message: "获取失败",
        }
      }
    } catch (error) {
      return error;
    }
  }
  async isExist(title: string) {
    try {
      const count = await this.albumModel.find({ title: title }).count()
      if (count == 0) {
        console.log("没有")
        return false
      }
      else {
        console.log("有")
        return true
      }
    } catch {
      return false
    }
  }
}